package com.usian.controller;

import com.usian.feign.CartFeign;
import com.usian.feign.ItemFeign;
import com.usian.pojo.TbItem;
import com.usian.utils.CookieUtils;
import com.usian.utils.JsonUtils;
import com.usian.utils.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
@RequestMapping("frontend/cart")
public class CartController {
    @Value("${CART_COOKIE_KEY}")
    private String CART_COOKIE_KEY;

    @Value("${CART_COOKIE_EXPIRE}")
    private Integer CART_COOKIE_EXPIRE;

    @Autowired
    private ItemFeign itemFeign;
    @Autowired
    private CartFeign cartFeign;

    @RequestMapping("addItem")
    public Result addItem(String userId, long itemId,
                          @RequestParam(defaultValue = "1") Integer num, HttpServletRequest request, HttpServletResponse response) {
        try {
            //判断是否登录
            if (StringUtils.isBlank(userId)) {
                //未登录在cookie中找购物车
                Map<String, TbItem> card = getCartFromCookie(request);


                //将商品添加到购物车
                addItemToCart(card, itemId, num);

                //再将购物车保存到cookie
                addClientCookie(request, response, card);

            } else {
                //已登录
                Map<String, TbItem> card =getCartFromRedis(userId);
                addItemToCart(card,itemId,num);
                Boolean boo=addCartToRedis(userId,card);
                if (boo){
                    return Result.ok();
                }
                return Result.error("添加失败");

            }

            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加失败");
        }

    }

    private Boolean addCartToRedis(String userId, Map<String, TbItem> card) {
        return cartFeign.addCartToRedis(userId,card);
    }

    private Map<String, TbItem> getCartFromRedis(String userId) {
        Map<String,TbItem> cart=cartFeign.getCartFromRedis(userId);

        if (cart!=null&&cart.size()>0){
            return cart;
        }
        return new HashMap<String, TbItem>();


    }

    private void addClientCookie(HttpServletRequest request, HttpServletResponse response, Map<String, TbItem> card) {
        String cardjson = JsonUtils.objectToJson(card);

        CookieUtils.setCookie(request, response, CART_COOKIE_KEY, cardjson, CART_COOKIE_EXPIRE, true);
    }

    private void addItemToCart(Map<String, TbItem> card, long itemId, Integer num) {
        //判断购物车是否有该商品
        TbItem tbItem = card.get(Long.toString(itemId));
        if (tbItem != null) {
            //商品存在就将数量累加
            tbItem.setNum(tbItem.getNum() + num);

        } else {
            //商品不存在则在数据库查找并添加到购物车
            tbItem = itemFeign.selectItemInfo(itemId);
            tbItem.setNum(num);

        }
        card.put(Long.toString(itemId), tbItem);

    }

    private Map<String, TbItem> getCartFromCookie(HttpServletRequest request) {
        String cookieValue = CookieUtils.getCookieValue(request, CART_COOKIE_KEY, true);
        if (StringUtils.isNotBlank(cookieValue)) {
            //购物车存在
            Map map = JsonUtils.jsonToMap(cookieValue, TbItem.class);
            return map;
        }
        return new HashMap<String, TbItem>();


    }

    @RequestMapping("showCart")
    public Result showCart(@RequestParam String userId, HttpServletRequest request) {
        try {
            List<TbItem> list = new ArrayList<>();
            if (StringUtils.isBlank(userId)) {
                //未登录

                Map<String, TbItem> cart = getCartFromCookie(request);
                Set<String> strings = cart.keySet();
                for (String string : strings) {
                    list.add(cart.get(string));
                }
            } else {
                //登陆
                Map<String, TbItem> cart = getCartFromRedis(userId);
                Set<String> strings = cart.keySet();
                for (String string : strings) {
                    list.add(cart.get(string));
                }

            }
            return Result.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败");
        }


    }


    @RequestMapping("updateItemNum")
    public Result updateItemNum(String userId, long itemId,
                                Integer num, HttpServletRequest request, HttpServletResponse response){

        try {
            //判断是否登录
            if (StringUtils.isBlank(userId)){
                //未登录
                //获取购物车
                Map<String, TbItem> cart = getCartFromCookie(request);
                TbItem tbItem = cart.get(Long.toString(itemId));
                tbItem.setNum(num);
                cart.put(Long.toString(itemId),tbItem);
                //将购物车放到cookie
                addClientCookie(request,response,cart);

            }else {
                //登录
                Map<String, TbItem> cart = getCartFromRedis(userId);
                TbItem tbItem = cart.get(Long.toString(itemId));
                tbItem.setNum(num);
                cart.put(Long.toString(itemId),tbItem);
                //将购物车放到cookie
                addClientCookie(request,response,cart);

            }
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("修改失败");

        }


    }

    @RequestMapping("deleteItemFromCart")
    public Result deleteItemFromCart(String userId, long itemId,
                                     Integer num, HttpServletRequest request, HttpServletResponse response){

        try {
            if (StringUtils.isBlank(userId)){
                Map<String, TbItem> cart = getCartFromCookie(request);
                cart.remove(Long.toString(itemId));
                addClientCookie(request,response,cart);
            }else {
                Map<String, TbItem> cart = getCartFromRedis(userId);
                cart.remove(Long.toString(itemId));
                addCartToRedis(userId,cart);


            }
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("删除失败");
        }
    }


    public Boolean gouwuchetongbu(HttpServletRequest request,String userid) {
        try {
            Map<String, TbItem> cartFromCookie = getCartFromCookie(request);
            Map<String, TbItem> cartFromRedis = getCartFromRedis(userid);
            for (String s : cartFromCookie.keySet()) {
                TbItem tbItem = cartFromCookie.get(s);
                addItemToCart(cartFromRedis,tbItem.getId(),tbItem.getNum());

            }
            addCartToRedis(userid,cartFromRedis);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }



    }
}
